package org.csu.mypetstore.service.impl;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.persistence.LineItemDao;
import org.csu.mypetstore.persistence.OrderDao;
import org.csu.mypetstore.persistence.impl.LineItemDaoImpl;
import org.csu.mypetstore.persistence.impl.OrderDaoImpl;
import org.csu.mypetstore.service.OrderService;
import org.csu.mypetstore.tools.MailSender;

import javax.mail.*;
import java.util.List;


public class OrderServiceImpl implements OrderService {
    OrderDao orderDao;
    LineItemDao lineItemDao;

    public OrderServiceImpl(){
        this.orderDao = new OrderDaoImpl();
        this.lineItemDao = new LineItemDaoImpl();
    }

    @Override
    public List<Order> getOrdersByUsername(String username) {
        return orderDao.getOrdersByUsername(username);
    }

    @Override
    public Order getOrder(int orderId) {
        return orderDao.getOrder(orderId);
    }

    @Override
    public void createOrder(Order order) {
        //创建新订单时需要插入两个表格
        orderDao.insertOrder(order);
        orderDao.insertOrderStatus(order);

        List<LineItem> lineItems = order.getLineItems();

        for(int i = 0; i < lineItems.size(); i++) {//将购物车的每一行都添加到订单数据库lineitem表中
            lineItemDao.insertLineItem(lineItems.get(i));
        }
    }

    @Override
    public void sendEmail(Account account, Cart order)  {
        try {
            MailSender mailSender = new MailSender();
            mailSender.sendEmail(account, order);
        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}
